package com.stu.wgt.test.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.stu.wgt.test.bean.Product;
import com.stu.wgt.test.bean.ProductCategories;
import com.stu.wgt.test.bean.ProductPictrurl;
import com.stu.wgt.test.result.R;
import com.stu.wgt.test.service.ProductCategoriesService;
import com.stu.wgt.test.service.ProductPictrurlService;
import com.stu.wgt.test.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wgt
 * @since 2024-01-20
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    ProductService productService;
    @Autowired
    ProductPictrurlService productPictrurlService;
    @Autowired
    ProductCategoriesService productCategoriesService;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public R addProduct(@RequestBody Product product) {
        try {
            // 获取图片的URL地址
            List<Map<String, String>> pictures = product.getPicture();
            int result = productService.insert(product);
            if (result == 1) {
//                List<Product> productList = productService.selectByName(product.getName());
                // 获取商品ID
                int id = product.getId();
                for (Map<String, String> picture : pictures) {
                    // 创建图片存储对象
                    ProductPictrurl productPictrurl = new ProductPictrurl();
                    productPictrurl.setProductId(id);
                    productPictrurl.setPictureUrl(picture.get("pictureUrl"));
                    productPictrurlService.insert(productPictrurl);
                }
                return R.ok().data("msg", "添加成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().data("msg", "添加失败");
        }
        return R.error();
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public R deleteProduct(@PathVariable("id") Integer id) {
        int result = productService.delete(id);
        if (result == 1) {
            return R.ok().data("msg", "删除成功");
        }
        return R.error().data("msg", "删除失败");
    }

    /**
     * 修改商品信息
     * @param product
     * @param id
     * @return
     */
    @RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
    public R updateProduct(@RequestBody Product product, @PathVariable("id") Integer id) {
        System.out.println("进入");
        product.setId(id);

        List<Map<String, String>> pictures = product.getPicture();
        ProductPictrurl pictrurl = new ProductPictrurl();
        pictrurl.setProductId(product.getId());
        if (pictures != null && !pictures.isEmpty()) {
            Map<String, String> pictureData = pictures.get(0);
            String picture = pictureData.get("picture");
            pictrurl.setPicture(picture);
            String pictureUrl = pictureData.get("pictureUrl");
            pictrurl.setPictureUrl(pictureUrl);
            productPictrurlService.updataByProductId(pictrurl);
        }
        product.setPicture(null);
        int result = productService.update(product);
        if (result == 1) {
            return R.ok().data("msg", "更新成功");
        }
        return R.error().data("msg", "更新失败");
    }

    // 更新库存


    @RequestMapping(value = "/selectById/{id}", method = RequestMethod.GET)
    public R selectById(@PathVariable("id") Integer id) {
        try {
            List<Product> productList = productService.selectById(id);
            List<ProductPictrurl> productPictrurlList = productPictrurlService.selectById(id);
            return R.ok().data("product", productList).data("picurl", productPictrurlList);
        } catch (Exception e) {
            return R.error().data("msg", "查询失败，请输入正确的ID");
        }
    }

    @RequestMapping(value = "/selectByIds/", method = RequestMethod.POST)
    public R selectByIds(@RequestBody List<Integer> ids) {
        try {
            List<Product> productList = productService.selectByIds(ids);
            return R.ok().data("product", productList);
        } catch (Exception e) {
            return R.error().data("msg", "查询失败，请输入正确的ID");
        }
    }

    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public R searchProduct(
            @RequestParam("query") String query,
            @RequestParam(value = "merchantId", required = false) Integer merchantId,
            @RequestParam("pagenum") Integer pageNum,
            @RequestParam("pagesize") Integer pageSize
    ) {
        try {
            System.out.println(query);
            IPage<Product> productIPage = productService.searchProduct(query, merchantId, pageNum, pageSize);
            return R.ok().data("product", productIPage.getRecords()).data("total", productIPage.getTotal());
        } catch (Exception e) {
            System.out.println(e);
            return R.error().data("msg", "查询失败，请更新查询参数");
        }
    }

    @GetMapping("/cate/{cate_id}")
    public R select(@PathVariable("cate_id") Integer id) {
        Integer[] as = new Integer[5];

        List<ProductCategories> productCategories = productCategoriesService.selectByParentId(id);

        int index = 0;
        for (ProductCategories productCategory : productCategories) {
            if (index < as.length) { // 确保不会超出数组 'as' 的界限
                as[index] = productCategory.getId();
                index++;
            } else {
                // 数组 'as' 已满，无法容纳更多的分类 ID。
                break; // 跳出循环
            }
        }
        System.out.println("as:" + as[1] + as[2] + as[0]);
        // 根据分类ID数组 as 来获取商品，并进行分页处理。
        int pageNum = 1; // 页码
        int pageSize = 20; // 页面大小
        List<Product> products = productService.selectCategoriesWithParentId(as, pageNum, pageSize);
        return R.ok().data("product", products);
    }

    @RequestMapping(value = "/category/{name}", method = RequestMethod.GET)
    public R category(@PathVariable("name") String name) {
        try {
            int cateId = productCategoriesService.selectByName(name);
            List<Product> productList = productService.selectByCate(cateId);
            return R.ok().data("product", productList);
        } catch (Exception e) {
            return R.error();
        }
    }

    /**
     * 商品图片上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R handleFileUpload(@RequestParam("file") MultipartFile file) {
        System.out.println("上传文件");
        try {
            String uploadDir = "E:/桌面/毕业设计/代码/后端/src/main/resources/static/image/";
            String originalFileName = file.getOriginalFilename();
            String fileExtension = "";

            // 获取文件后缀（扩展名）
            if (originalFileName != null && originalFileName.lastIndexOf(".") != -1) {
                fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            }
            String uuid = UUID.randomUUID().toString().replace("-", "");//UUID生成不重复的一串数字
            String newFileName = uuid + fileExtension; // 新的文件名 = UUID + 文件扩展名
//            // 处理中文文件名编码
//            String fileName = new String(originalFileName.getBytes("UTF-8"), "ISO-8859-1");

            File dest = new File(uploadDir + newFileName);
            file.transferTo(dest);

            String tmpPath = newFileName;
            String url = "http://127.0.0.1:8888/image/" + tmpPath;
            return R.ok().data("tmp_path", tmpPath).data("url", url);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }
}

